package com.example.weather_app.city_manager;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.weather_app.R;
import com.example.weather_app.db.DBManager;
import com.example.weather_app.db.DatabaseBean;
import com.example.weather_app.myadapter.CityManagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class CityManagerActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView backTv, deleteIv, addIv;
    private ListView cityLv;

    private List<DatabaseBean> databaseBeanList;
    private CityManagerAdapter cityManagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_manager);

        addIv = (ImageView) findViewById(R.id.city_add);
        backTv = (ImageView) findViewById(R.id.city_iv_back);
        deleteIv = (ImageView) findViewById(R.id.ciity_iv_delete);
        cityLv = (ListView) findViewById(R.id.city_lv);
        databaseBeanList = new ArrayList<>();

        //添加监听事件
        addIv.setOnClickListener(this);
        backTv.setOnClickListener(this);
        deleteIv.setOnClickListener(this);

        cityManagerAdapter = new CityManagerAdapter(this, databaseBeanList);
        cityLv.setAdapter(cityManagerAdapter);
    }

    /**
     * 获取数据库当中真实真实源，添加到原有数据源当中，提示适配器更新
     */
    @Override
    protected void onResume() {
        super.onResume();
        databaseBeanList.clear();
        databaseBeanList.addAll(DBManager.queryAllInfo());
        cityManagerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        Intent it = null;
        switch (v.getId()) {
            case R.id.city_add:
                if (DBManager.getCityCount()<5) {
                    it = new Intent(this,SearchCityActivity.class);
                    startActivity(it);
                }else{
                    Toast.makeText(this, "存储城市数量已达上限，请删除后再增加", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.city_iv_back:
                finish();
                break;
            case R.id.ciity_iv_delete:
                it = new Intent(this,DeleteCityActivity.class);
                startActivity(it);
                break;
        }
    }
}